<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>ESP32 OTA</title>
    <meta name='viewport' content='width=device-width, initial-scale=1' />
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src='js/jquery-3.3.1.min.js'></script>
</head>

<body>
    <div class="topnav" id="myTopnav">
        <a href="#" class="disabled">ESP Web Server</a>
        <div class="topnav-right">
          <a href="wifimanager">WiFi Manager</a>
          <a href="ota">OTA</a>
          <a href="/">Home</a>
        </div>
        <a href="javascript:void(0);" class="icon" onclick="handleNavBar()">
          <i class="fa fa-bars"></i>
        </a>
    </div>
    <h2>ESP32 Firmware Update Page</h2>
		<h4 id="latest_firmware"></h4>
		
    <input type="file" id="selectedFile" accept=".bin" style="display: none;" onchange="myFunction()" />
    <input type="button" value="Browse..." onclick="document.getElementById('selectedFile').click();" />
    <h3 id="file_info"></h3>
    <input type='submit' id="upload_button" value='Update Firmware' onclick="updateFirmware()"><br>
    <p>
    <button onclick="rebootButton()">Reboot</button>
    </p>

    <h4 id="status"></h4>
    <h4 id="status1"></h4>
    <h4 id="statusdetails"></h4>

    <script>
        var seconds;
        var mytimerVar;
        
			$(document).ready(function ()
			{
				//console.log('OTA READY')
				// Request this first so we can show the current Firmware in the unit
				getstatus();

			});        
        
  
        function myFunction() {
            var x = document.getElementById("selectedFile");
            var file = x.files[0];

            document.getElementById("file_info").innerHTML = "<h4>File: " + file.name + "<br>" + "Size: " + file.size + " bytes</h4>";
        }

        function updateFirmware() {
            // Form Data
            var formData = new FormData();

            var fileSelect = document.getElementById("selectedFile");
            
            if (fileSelect.files && fileSelect.files.length == 1) {
                var file = fileSelect.files[0];
                formData.set("file", file, file.name);
                document.getElementById("status").innerHTML = "Uploading " + file.name + " , Please Wait...";

                // Http Request
                var request = new XMLHttpRequest();

                request.upload.addEventListener("progress", updateProgress);

                request.open('POST', "/update");
                request.responseType = "blob";
                request.send(formData);
            } else {
                window.alert('Select A File First')
            }
        }

        // progress on transfers from the server to the client (downloads)
        function updateProgress(oEvent) {
            if (oEvent.lengthComputable) {
                getstatus();
            } else {
                window.alert('total size is unknown')
            }
        }

        function getstatus() {
            var xhr = new XMLHttpRequest();
            var requestURL = "/status";
            xhr.open('POST', requestURL, false);
            xhr.send('status');
            if (xhr.readyState == 4 && xhr.status == 200) {
                var response = JSON.parse(xhr.responseText);
								
								 document.getElementById("latest_firmware").innerHTML ="Latest Firmware:  " + response.compile_date + " - " + response.compile_time

								// If flashing was complete it will return a 1, else -1
								// A return of 0 is just for information on the Latest Firmware request
                if (response.status == 1) {
                		// Init the countdown timer time
                    seconds = 10;
                    // Start the countdown timer
                    startMyTimer();
                } 
                else if (response.status == -1){
                    document.getElementById("status").innerHTML = "!!! Upload Error !!!";
                }
            }
        }

        function startMyTimer() {
            document.getElementById("status").innerHTML = "Flashing Complete, Reboot in: " + seconds;

            if (--seconds == 0) {
                clearTimeout(mytimerVar);

                window.location.reload();
            } else {
                mytimerVar = setTimeout(startMyTimer, 1000);
            }
        }
        function rebootButton() {
            document.getElementById("statusdetails").innerHTML = "Invoking Reboot ...";
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "/reboot", true);
            xhr.send();
            window.open("/reboot","_self");
        }
    </script>
</body>
</html>